﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;


using System.Diagnostics;
using System.IO;
using CStock;
using CUtil;
using CIndicators;


namespace CTrading
{
    public partial class DialogProfile : Form
    {
        private IDataItem dataItem;
        IProfile profileOld;
        private bool doNotRefreshTree;
        private string comboBoxSelectionOld;


        public DialogProfile(IDataItem myDataItem)
        {
            dataItem = myDataItem;
            if (!Profile.CheckProfile(dataItem))
            {
                System.Windows.Forms.MessageBox.Show("SW Error: No valid Profile found");

            }
            else
            {
                InitializeComponent();
                InitializeCustom();
                profileOld = this.dataItem.Profile;
            }
        }
        public IDataItem DataItem
        {
            get
            {
                return this.dataItem;
            }
          
        }


        private void SetSelectionInCombo(string sel )
        {
            for (int i = 0; i < this.comboBoxProfileSelector.Items.Count; i++)
            {

               if( this.comboBoxProfileSelector.Items[i].ToString() == sel)
                   this.comboBoxProfileSelector.SelectedIndex = i;
                
            }
        }
        private bool InitComboBox()
        {
            string selectedText = this.dataItem.ProfileName;
            

            IList<string> strEntries = Profile.GetProfiles();
            for (int i = 0; i < strEntries.Count; i++)
            {
                
                this.comboBoxProfileSelector.Items.Add(strEntries[i]);
                //doNotRefreshTree = true;
                if (strEntries[i] == selectedText)
                {
                    
                    this.comboBoxProfileSelector.SelectedIndex = i;
                }
            }

            return true;

        }
        private bool InitTree()
        {
            this.treeViewStockBase1.Nodes.Clear();
            TreeNode nod = new TreeNode("MainChart: " + this.dataItem.Name);
            nod.Tag = "ChartNode";
            this.treeViewStockBase1.Nodes.Add(nod);
            nod = new TreeNode("2nd Chart");
            nod.Tag = "ChartNode";
            this.treeViewStockBase1.Nodes.Add(nod);
            nod = new TreeNode("3rd Chart");
            nod.Tag = "ChartNode";
            this.treeViewStockBase1.Nodes.Add(nod);
            
            return true;
        }
        private void CheckButtons()
        {
            if (this.comboBoxProfileSelector.Items.Count < 2 ||
                (this.comboBoxProfileSelector.SelectedItem != null && this.comboBoxProfileSelector.SelectedItem.ToString() == "Default"))
            {
                this.buttonProfileDelete.Enabled = false;
                this.buttonProfileRename.Enabled = false;
            }
            else
            {
                this.buttonProfileDelete.Enabled = true;
                this.buttonProfileRename.Enabled = true;
            }
        }
        private bool InitializeCustom()
        {
            try
            {
                InitComboBox();
                InitTree();
                FillTreeFromProfile();
                CheckButtons();


                return true;
            }
            catch (Exception err)
            {
                Debug.Assert(false, "Error initializing custom properties of Dialog Profile : " + err.Message);
                return false;
            }
        }
        private void ModifyChartLine()
        {
        }
        
        private void AddNewChartLine()
        {
            DialogChartLine dcl = new DialogChartLine(this.dataItem);
            if (dcl.ShowDialog() == DialogResult.OK)
            {
                IIndicator ind = dcl.Indicator;
                IDataItem di = dcl.DataItemNew;
                if (ind != null)
                {
                    TreeNode nod = new TreeNode(ind.Name);
                    nod.Tag = "INDICATOR";
                    this.treeViewStockBase1.SelectedNode.Nodes.Add(nod);
                }
                else if (di != null)
                {
                    TreeNode nod = new TreeNode(di.ID);
                    nod.Tag = "SHARE";
                    this.treeViewStockBase1.SelectedNode.Nodes.Add(nod);
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show("SW Error - in configuring Chart line");
                }
                this.treeViewStockBase1.SelectedNode.ExpandAll();
            }
        }
     

        private void toolStripMenuItemAddLine_Click(object sender, EventArgs e)
        {
            if (this.treeViewStockBase1.SelectedNode.Level == 0)
                AddNewChartLine();

        }

        private void toolStripMenuItemDelete_Click(object sender, EventArgs e)
        {

            if (this.treeViewStockBase1.SelectedNode.Level > 0) 
                this.treeViewStockBase1.SelectedNode.Remove();

        }

        private void toolStripMenuIModify_Click(object sender, EventArgs e)
        {
            if (this.treeViewStockBase1.SelectedNode.Level > 0) 
                ModifyChartLine();

        }

        private void toolStripMenuMoveUp_Click(object sender, EventArgs e)
        {

        }

        private void toolStripMenuMoveDown_Click(object sender, EventArgs e)
        {

        }

        private void contextMenuTree_Opening(object sender, CancelEventArgs e)
        {
           if (this.treeViewStockBase1.SelectedNode.Level == 0) 
           {
               
               this.toolStripMenuItemAddLine.Enabled = true;

                toolStripMenuItemDelete.Enabled = false;
                this.toolStripMenuIModify.Enabled = false;
                this.toolStripMenuMoveDown.Enabled = false;
               
                 this.toolStripMenuMoveUp.Enabled = false;
                

            }
            else
            {
                //toolStripMenuItemDelete.Visible = true;
                this.toolStripMenuItemAddLine.Enabled = false;

                toolStripMenuItemDelete.Enabled = true;
                this.toolStripMenuIModify.Enabled = true;
                this.toolStripMenuMoveDown.Enabled = true;
                this.toolStripMenuMoveUp.Enabled = true;
               if(this.treeViewStockBase1.SelectedNode.Text.Contains("MainChart:" ))
                   this.toolStripMenuMoveUp.Enabled = false;
               if (this.treeViewStockBase1.SelectedNode.Text.Contains("3rd Chart"))
                   this.toolStripMenuMoveDown.Enabled = false;

            }
        }

        private void treeViewStockBase1_KeyUp(object sender, KeyEventArgs e)
        {
       
			base.OnKeyUp(e);
            Keys keyData = e.KeyData;
			
			//System.Diagnostics.Debug.WriteLine("KKK " + Control.ModifierKeys.ToString() + ";" + keyData);
			if (Control.ModifierKeys == Keys.Control && keyData == Keys.C)
			{
				MessageBox.Show("Ctrl-C");
			}

			switch (keyData) 
			{
				case Keys.ControlKey:
				{
					System.Diagnostics.Debug.WriteLine("Key-Control-Up = "+keyData.ToString());
					
					break;
				}
				case Keys.C:
				{
                    //System.Diagnostics.Debug.WriteLine("Key-C-Up = "+keyData.ToString()+
                    //    "Modifiers="+e.Modifiers.ToString());
					if (e.Control)
					{
						//TreeNodeStock copyTreeNode= (TreeNodeStock) this.SelectedNode;
						//System.Diagnostics.Debug.WriteLine("SelectedNode = "+copyTreeNode);
					}
                    //else
                    //{System.Diagnostics.Debug.WriteLine("KeyEvent-Up = "+e.ToString());}
                    break;
				}
				case Keys.V:
				{
					//System.Diagnostics.Debug.WriteLine("Key-V-Up = "+keyData.ToString());
					break;
				}
				case  Keys.Delete:
				{
                    if(this.treeViewStockBase1.SelectedNode.Level > 0)
                        this.treeViewStockBase1.SelectedNode.Remove();

					break;
				}
                case Keys.Insert:
                {
                    if (this.treeViewStockBase1.SelectedNode.Level == 0)
                        AddNewChartLine();
                    break;
                }
                
				default:
				{
					System.Diagnostics.Debug.WriteLine("Key-Default-Up = "+keyData.ToString());
					//Debug.Assert(false,"Key undefined or not used - "+keyData.ToString());
					break;
				}
			}
            this.treeViewStockBase1.Refresh();
		
		
        }
        private void SaveProfile(string newID)
        {
            try
            {
                IProfile myProfile = new Profile();
                myProfile.ID = newID;
                myProfile.ChartLine = new List<ChartLine>();

                for (int i = 0; i < this.treeViewStockBase1.Nodes.Count; i++)
                {
                    TreeNode tnMain = this.treeViewStockBase1.Nodes[i];

                    for (int j = 0; j < tnMain.Nodes.Count; j++)
                    {
                        TreeNode tnChild = tnMain.Nodes[j];
                        ChartLine cl = new ChartLine();
                        cl.ChartNumber = i;
                        cl.IndicatorOrShareName = tnChild.Text;
                        if (tnChild.Tag != null)
                        {
                            if (tnChild.Tag.ToString() == "SHARE")
                            {
                                cl.IsEquity = true;
                            }
                            else
                            {
                                cl.IsEquity = false;
                            }
                        }
                        myProfile.ChartLine.Add(cl);

                    }
                }
                myProfile.Serialize();
                this.dataItem.ProfileName = newID;
                //will update also profile (see property setter from DataIatem!
            }
            catch (Exception ex)
            {
                Debug.Assert(false, "Error saving Profile : " + ex.Message);
            }
            
        }
        private void FillTreeFromProfile()
        {

            if (this.dataItem.Profile.ChartLine != null)
            {
                for (int i = 0; i < this.dataItem.Profile.ChartLine.Count; i++)
                {
                    ChartLine cl = this.dataItem.Profile.ChartLine[i];
                    TreeNode tn = new TreeNode(cl.IndicatorOrShareName);
                    if (cl.IsEquity)
                    {
                        tn.Tag = "SHARE";

                    }
                    else
                    {
                        tn.Tag = "INDICATOR";
                    }
                    this.treeViewStockBase1.Nodes[cl.ChartNumber].Nodes.Add(tn);

                }
            }
            this.treeViewStockBase1.ExpandAll();
        }
        private void buttonOK_Click(object sender, EventArgs e)
        {
            if (profileOld != this.dataItem.Profile)
            {
                this.dataItem.ProfileName = this.dataItem.Profile.ID;
                IPortfolio port = this.dataItem.Parent as IPortfolio;
                port.Serialize();

            }
           
                SaveProfile(this.dataItem.ProfileName);
            
        }
        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            if (this.DialogResult != DialogResult.OK)
            {
                this.dataItem.ProfileName = this.profileOld.ID;
            }
            base.OnFormClosed(e);
        }
        private void SelectInComboBox(string selection)
        {
            for (int i = 0; i < this.comboBoxProfileSelector.Items.Count; i++)
            {
                string str = this.comboBoxProfileSelector.Items[i] as string;
                if (str == selection)
                {
                    this.comboBoxProfileSelector.SelectedIndex = i;
                    break;
                }
            }

        }
        private string CreateNewProfileName(string nameBase, ref int i)
        {
            i++;
            string strName = nameBase + i.ToString() + ")";
            if (this.comboBoxProfileSelector.Items.Contains(strName))
            {
                return CreateNewProfileName(nameBase, ref i);
            }
            return strName;

        }
        
        private void RefreshAll()
        {
            string strSelection = this.comboBoxProfileSelector.SelectedItem.ToString();
            if (comboBoxSelectionOld != strSelection)
            {
                this.dataItem.ProfileName = strSelection;
                InitTree();
                FillTreeFromProfile();
                CheckButtons();
                doNotRefreshTree = false;
            }
        }
        private void comboBoxProfileSelector_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (! this.doNotRefreshTree)
            {
                RefreshAll();
                
            }
            doNotRefreshTree = false;
            if(this.comboBoxProfileSelector.SelectedItem != null)
                comboBoxSelectionOld = this.comboBoxProfileSelector.SelectedItem.ToString();
        }

        private void comboBoxProfileSelector_DropDown(object sender, EventArgs e)
        {
            if(this.comboBoxProfileSelector.SelectedItem != null)
                comboBoxSelectionOld = this.comboBoxProfileSelector.SelectedItem.ToString();
        }

        private void buttonProfileDelete_Click(object sender, EventArgs e)
        {
            MessageBoxButtons buttons = MessageBoxButtons.YesNo;
            string strProfile = this.comboBoxProfileSelector.SelectedItem.ToString();
            if (System.Windows.Forms.MessageBox.Show("Really delete: " + strProfile ,  "Delete?? ", buttons) == DialogResult.Yes)
            {
                this.dataItem.Profile.Delete();
                comboBoxSelectionOld = this.comboBoxProfileSelector.SelectedItem.ToString();
                this.comboBoxProfileSelector.Items.Remove(this.comboBoxProfileSelector.SelectedItem);
                if (this.comboBoxProfileSelector.Items.Count > 0)
                {
                    this.comboBoxProfileSelector.SelectedItem = this.comboBoxProfileSelector.Items[0];
                    this.dataItem.ProfileName = this.comboBoxProfileSelector.SelectedItem.ToString();
                    RefreshAll();
                }


            }
            
            

        }
        private void buttonProfileNew_Click(object sender, EventArgs e)
        {
            IProfile profileNew = new Profile();
            int i = 0;
            profileNew.ID = CreateNewProfileName("New(", ref i);

            if (this.comboBoxProfileSelector.Items.Contains(profileNew.ID))
            {
                System.Windows.Forms.MessageBox.Show("New profile already in list - please rename");
            }
            else
            {
                profileNew.Serialize();
                this.dataItem.ProfileName = profileNew.ID;
                this.comboBoxProfileSelector.Items.Add(profileNew.ID);
                SelectInComboBox(profileNew.ID);
                CheckButtons();

            }


        }
        private void buttonProfileCopy_Click(object sender, EventArgs e)
        {
            ICloneable cl = this.dataItem.Profile as ICloneable;

            IProfile profileNew = cl.Clone() as IProfile;
            
            int i = 0;
            profileNew.ID = CreateNewProfileName("Copy(", ref i);

            if (this.comboBoxProfileSelector.Items.Contains(profileNew.ID))
            {
                System.Windows.Forms.MessageBox.Show("This profile is already in list - please rename");
            }
            else
            {
                profileNew.Serialize();
                this.dataItem.ProfileName = profileNew.ID;
                this.comboBoxProfileSelector.Items.Add(profileNew.ID);
                SelectInComboBox(profileNew.ID);
                CheckButtons();


            }
        }

        private void buttonProfileRename_Click(object sender, EventArgs e)
        {
            string strSelection = this.comboBoxProfileSelector.Text;
            
            bool bfound = false;
            for(int i = 0; i <this.comboBoxProfileSelector.Items.Count; i++)
            {
                if( this.comboBoxProfileSelector.Items[i].ToString() == strSelection)
                {
                    System.Windows.Forms.MessageBox.Show("Please choose another name - name already set");
                    bfound = true;
                    break;
                }
            }
            
            if(! bfound)
            {
                this.dataItem.Profile.Delete();
                this.dataItem.Profile.ID = strSelection;
                this.dataItem.Profile.Serialize();
                this.dataItem.Parent.Serialize();
                this.comboBoxProfileSelector.Items.Remove(comboBoxSelectionOld);
                this.comboBoxProfileSelector.Items.Add(strSelection);
                
                comboBoxProfileSelector.DropDownStyle = ComboBoxStyle.DropDown;
                buttonProfileCopy.Enabled = true;
                buttonProfileDelete.Enabled = true;
                buttonProfileNew.Enabled = true;
                SetSelectionInCombo(strSelection);


                //this.dataItem.Profile.Serialize();    

            }
        }
        private void comboBoxProfileSelector_KeyDown(object sender, KeyEventArgs e)
        {
            comboBoxProfileSelector.DropDownStyle = ComboBoxStyle.Simple;
            buttonProfileRename.Enabled = true;
            buttonProfileCopy.Enabled = false;
            buttonProfileDelete.Enabled = false;
            buttonProfileNew.Enabled = false;
        }   
    }
}
